package jwdt.xadmin.work.service.impl;

import java.util.ArrayList;
import java.util.List;

import jwdt.common.bean.Tree;
import jwdt.common.dao.BaseDao;
import jwdt.common.util.CacheUtil;
import jwdt.xadmin.system.bean.TUser;
import jwdt.xadmin.work.bean.TEmail;
import jwdt.xadmin.work.service.EmailManageService;

import com.ezerg.db.DataMap;
import com.ezerg.db.Jdb;
import com.ezerg.db.ext.PageUtil;
import com.ezerg.email.EmailMaker;
import com.ezerg.email.SimpleEmail;
import com.ezerg.util.DateUtil;
import com.ezerg.util.StringUtil;

public class EmailManageServiceImpl implements EmailManageService{

	private BaseDao<TEmail> baseDao;
	
	public void setBaseDao(BaseDao<TEmail> baseDao) {
		this.baseDao = baseDao;
	}
	
	@Override
	public PageUtil doInList(PageUtil pu,TUser userInfo,String zt) throws Exception{
		String sql = "SELECT a.emailid, a.userid, a.isread, b.sender, b.receiver, b.title, b.cc, b.content, b.dt FROM t_email_inbox a, t_email b WHERE a.emailid=b.emailid AND a.userid="+userInfo.getUserid()+" AND a.zt in ("+zt+") order by b.dt desc";
		pu.doList(sql);
		//创造json数据对象
		return pu; 
	}
	
	public PageUtil doOutList(PageUtil pu,TUser userInfo,String zt) throws Exception{
		String sql = "SELECT emailid,sender,receiver,cc,title,content,dt,zt FROM t_email a WHERE userid="+userInfo.getUserid()+" and zt in ( "+zt+") order by dt desc";
		pu.doList(sql);
		//创造json数据对象
		return pu;
	}
	
	@Override
	public PageUtil doListUserEmailState(PageUtil pu, int id, String zt)
			throws Exception {
		String sql = "SELECT e.sender, (SELECT username FROM t_user WHERE userid=i.userid) AS receiver,isread,replyid FROM t_email_inbox i,t_email e WHERE i.emailid=e.emailid AND i.emailid="+id;
		pu.doList(sql);
		//创造json数据对象
		return pu;
	}
	
	@Override
	public String doGetNewEmail(TUser userInfo)
			throws Exception {
		String sql = "SELECT count(emailid) FROM t_email_inbox WHERE zt=0 AND isread=0 AND userid="+userInfo.getUserid()+" LIMIT 1";
		return Jdb.get().queryForString(sql);
	}
	
	@Override
	public TEmail doLoad(int id) throws Exception {
		return baseDao.doLoadObj(TEmail.class, id);
	}
	
	@Override
	public List<Tree> doLeftTree() throws Exception {
		List<Tree> l = new ArrayList<Tree>(1);
		List<Tree> l2 = new ArrayList<Tree>(2);
		Tree tree = new Tree();
		tree.setId("0");
		tree.setText("我的消息");
		tree.setIconCls("icon-users");
		tree.setState("open");
		tree.setChildren(l2);
		Tree in = new Tree();
		in.setId("1");
		in.setText("收件箱");
		l2.add(in);
		Tree outx = new Tree();
		outx.setId("2");
		outx.setText("草稿箱");
		l2.add(outx);
		Tree out = new Tree();
		out.setId("3");
		out.setText("已发送");
		l2.add(out);
		Tree inx = new Tree();
		inx.setId("4");
		inx.setText("已删除");
		l2.add(inx);
		//
		l.add(tree);
		return l;
	}
	
	@Override
	public String doAddact(TEmail obj,TUser userInfo,int zt,int oldemailid) throws Exception {
		String dateTime = DateUtil.getDateTime();
		int userid = userInfo.getUserid();
		obj.setUserid(userid);
		obj.setSender(userInfo.getUsername());
		obj.setDt(dateTime);
		obj.setZt(zt);//发送
		String ret = baseDao.doAddObj(obj);
		if("添加成功".equals(ret) && zt==1) {
			int emailid = Jdb.get().queryForInt("select emailid from t_email where userid=? and dt=?", new Object[]{userid,dateTime});
			ret = doSendEmail(emailid);
			if(oldemailid != 0) {//回复
				doUpdateEmailState(oldemailid, userid, "reply");
				Jdb.get().execute("update t_email_inbox set replyid=? where userid=? and emailid=?", new Object[]{oldemailid,userid,emailid});
			}
		}
		return ret;
	}

	@Override
	public String doEditact(TEmail obj, int emailid,int zt) throws Exception {
		String dateTime = DateUtil.getDateTime();
		obj.setDt(dateTime);
		obj.setZt(zt);//发送
		String ret = baseDao.doUpdateObj(TEmail.class, emailid, obj);
		if("修改成功".equals(ret) && zt==1) {
			ret = doSendEmail(emailid);
		}
		return ret;
	}
	
	@Override
	public String doSendEmail(int emailid) throws Exception {
		String ret = "发送成功";
		try {
			TEmail obj = (TEmail)Jdb.get().get(TEmail.class, emailid);
			if(obj == null) return "您发送的消息不存在！";
			String[] receiverid = obj.getReceiverids().split(",");
			for (String userId : receiverid) {
				Jdb.get().execute("insert into t_email_inbox(userid,emailid,zt) values(?,?,?)", new Object[]{userId, emailid, "0"});
			}
		} catch (Exception e) {
			ret = "发送失败";
			e.printStackTrace();
		}
		return ret;
	}
	
	@Override
	public String doDelact(int id,TUser userInfo) throws Exception {
		String ret = "删除成功";
		int count = Jdb.get().queryForInt("select count(emailid) from t_email_inbox where emailid ="+id);
		if(count == 0){// 收件删除
			ret = baseDao.doDelObj(TEmail.class, id);
		} else {
			ret = baseDao.doIntUpdateState(TEmail.class, "emailid="+id, "zt=2");
		}
		return ret;
	}

	@Override
	public String doUpdateEmailState(int id, int userid, String flag) throws Exception {
		String ret = "操作成功";
		try {
			if("read".equals(flag)) {//已读
				Jdb.get().execute("update t_email_inbox set isread=1 where emailid=? and userid=? ",new Object[]{id, userid});
			}
			else if("reply".equals(flag)) {//回复
				Jdb.get().execute("update t_email_inbox set isread=2 where emailid=? and userid=? ",new Object[]{id, userid});
			}
			else if("inbox".equals(flag)) {//收件
				Jdb.get().execute("update t_email_inbox set zt=0 where emailid=? and userid=? ",new Object[]{id, userid});
			}
			else if("deleted".equals(flag)) {//删除
				Jdb.get().execute("update t_email_inbox set zt=1 where emailid=? and userid=? ",new Object[]{id, userid});
			}
			else if("delete".equals(flag)) {//
				Jdb.get().execute("delete from t_email_inbox where emailid=? and userid=?", new Object[]{id, userid});
				int count = Jdb.get().queryForInt("select count(emailid) from t_email_inbox where emailid ="+id);
				TEmail e = (TEmail)baseDao.doLoadObj(TEmail.class, id);
				if(count == 0 && e!=null && e.getZt()==2){//发件已删除
					ret = baseDao.doDelObj(TEmail.class, id);
				}			
			}
		} catch(Exception e) {
			ret = "操作出错";
			e.printStackTrace();
		}
		return ret;
	}
	
	@Override
	@SuppressWarnings("unchecked")
	public String doLoadReceiver(int emailid,TUser userInfo) throws Exception {
		StringBuffer s = new StringBuffer();
		try {
			TEmail e = (TEmail)baseDao.doLoadObj(TEmail.class, emailid);
			String cc = e.getCc();
			if(StringUtil.nullOrBlank(cc)) {
				List<String> emails = Jdb.get().querySingle("select userEmail from t_user where userid in ("+e.getReceiverids()+")");
				for (String receiver : emails) {
					if(!StringUtil.nullOrBlank(receiver)){
						s.append(receiver+";");
					}
				}
			} else {
				s.append(cc);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return s.toString();
	}
	
	@Override
	public String doSendRealEmail(TEmail obj, TUser userInfo,String receiver) throws Exception {
		String ret = "发送成功";
		try {
			baseDao.doUpdateObj(TEmail.class, obj.getEmailid(), obj);
			//
			DataMap dm = Jdb.get().queryDataMap("select * from t_email_set where userid=?",new Object[]{userInfo.getUserid()},CacheUtil.C0);
			SimpleEmail email =EmailMaker.get(dm).getSimpleEmail();
			email.addTo(receiver.split(";"));
			email.setFrom(dm.getString("username"), userInfo.getUsername());
			email.setSubject(obj.getTitle());
			email.setMsg(obj.getContent());
			email.send();
		} catch (Exception e) {
			ret = "发送失败";
			e.printStackTrace();
		}
		return ret;
	}
}
